package com.cw.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.cw.data.ConstantEnum;
import com.cw.data.Result;
import com.cw.pojo.SpecVO;
import com.cw.pojo.TbSpecification;
import com.cw.pojo.TbSpecificationOption;
import com.cw.pojo.TbTypeTemplate;
import com.cw.service.SpacificationService;
import com.cw.service.TemplateService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("typeController")
public class TypeController {

    @Reference
    private TemplateService templateService;

    @Reference
    private SpacificationService spacificationService;

    @RequestMapping("getOneType")
    @ResponseBody
    public Result getOneType(Long typeId) {

        try {

            TbTypeTemplate tt = templateService.getOneTemplate(typeId);

            return Result.result(ConstantEnum.SUCCESS).setData(tt);

        }catch (Exception e) {

            e.printStackTrace();

            return Result.result(ConstantEnum.ERROR);
        }
    }

    @RequestMapping("getSpecInfo")
    @ResponseBody
    public Result getSpecInfo(Long typeId) {

        try {

            if (typeId != null) {

                TbTypeTemplate tt = templateService.getOneTemplate(typeId);

                List<TbSpecification> specificationList = JSONObject.parseArray(tt.getSpecIds(), TbSpecification.class);

                List<SpecVO> collect = specificationList.stream().map(s -> {

                    SpecVO specVO = spacificationService.getOneSpecInfo(s.getId());

                    return specVO;

                }).collect(Collectors.toList());

                return Result.result(ConstantEnum.SUCCESS).setData(collect);
            }else {

                return null;
            }

        }catch (Exception e) {

            e.printStackTrace();

            return Result.result(ConstantEnum.ERROR);
        }
    }
}
